import {useRef, useEffect, useState, useMemo} from 'react';
import {useFrame} from '@react-three/fiber';
import * as THREE from 'three';

export default function Box(props) {
  const boxRef = useRef(null);
  const [hovered, setHovered] = useState(false);
  const [color, setColor] = useState(0x00ff00);

  // const geometry = new THREE.BoxGeometry(2, 2, 2);
  // const geometry = useMemo(() => new THREE.BoxGeometry(2, 2, 2), []);
  const [count, setCount] = useState(0);
  const geometries = useMemo(() =>
    [new THREE.BoxGeometry(2, 2, 2), new THREE.SphereGeometry(1)], [count]);

  useEffect(() => {
    // console.log('Box position: ', boxRef.current.name, boxRef.current.position);
    console.log('Box uuid: ', boxRef.current.geometry.uuid);
  }, [boxRef.current]);

  useFrame((state, delta) => {
    if (boxRef.current && !hovered) {
      boxRef.current.rotation.x += delta;
      boxRef.current.rotation.y += 0.5 * delta;
      boxRef.current.position.y = Math.sin(state.clock.getElapsedTime());
    }
  });

  const boxClick = (e) => {
    console.log('Box clicked!', e.object.name);
    setCount((count + 1) % 2);
  };

  const pointOver = () => {
    setHovered(true);
    setColor(0xff0000);
  };

  const pointOut = () => {
    setHovered(false);
    setColor(0x00ff00);
  };

  return (
    <mesh
      ref={boxRef}
      position={props.position}
      scale={hovered ? [1.1, 1.1, 1.1] : [1, 1, 1]}
      name={props.name}
      onPointerDown={boxClick}
      onPointerUp={(e) => console.log('Box released!', e.object.name)}
      onPointerOver={() => pointOver(true)}
      onPointerOut={() => pointOut(false)}
      geometry={geometries[count]}
    >
      {/* <boxGeometry args={[2, 2, 2]}/> */}
      <meshBasicMaterial color={color} wireframe={props.wireframe}/>
    </mesh>
  );
}
